
package com.tools.cleanmaster.model.cloud;

import android.util.Pair;

import com.tools.cleanmaster.CleanApplication;
import com.tools.cleanmaster.model.db.TrashDB;
import com.tools.cleanmaster.model.item.FilePathBean;
import com.tools.cleanmaster.model.item.PathUpdateInfo;
import com.tools.cleanmaster.model.language.LanguageCompat;
import com.tools.cleanmaster.store.TrashCloudSharedPrefManager;
import com.tools.cleanmaster.utils.FeatureConfig;
import com.tools.cleanmaster.utils.LogHelper;
import com.tools.cleanmaster.utils.NetworkUtils;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class TrashQueryPathManager {
    private static final long TIME_QUERY_INTERVAL = 8L * 3600 * 1000;
    private volatile boolean mChecking = false;
    private volatile boolean mIsQuering = false;
    private volatile static TrashQueryPathManager mInstance = new TrashQueryPathManager();
    private static final String URLClOUD =  "";
    private static final String URLDB =  "";
    private static final String URLUNKNOW =  "";

    private TrashQueryPathManager() {
    }

    public static TrashQueryPathManager getInstance() {
        return mInstance;
    }

    class UploadTask extends TimerTask {

        @Override
        public void run() {
            if (mChecking) {
                return;
            }
            mChecking = true;
            if (canDoQuery()) {
                startQuery(TrashCloudSharedPrefManager.getUpdateTimes());
            }
            mChecking = false;
        }
    }

    /**
     * 检查查询条件，是否满足
     * 1. 有网络
     * 2. 8小时间隔
     *
     * @return
     */
    private boolean canDoQuery() {
        if (!NetworkUtils.isNetworkAvaialble(CleanApplication.getInstance())) {
            return false;
        }

        final long now = System.currentTimeMillis();
        long lastUpdateTime = TrashCloudSharedPrefManager.getUpdateTime();
        // 如果从未进行过检查，则写下当前的时间，8小时后进行才可以进行查询
        if (lastUpdateTime == 0) {
            TrashCloudSharedPrefManager.setUpdateTime(now);
            return false;
        }

        final long interval = now - lastUpdateTime;

        if (FeatureConfig.DEBUG_LOG && interval < TIME_QUERY_INTERVAL) {
            LogHelper.i(TrashPostContant.TAG, "未到8小时=====");
        }

        return (interval >= TIME_QUERY_INTERVAL);
    }

    /**
     * 应用第一次启动时候调用这个
     */
    public void startUpdataTask() {
        Timer timer = new Timer();
        timer.schedule(new UploadTask(),
                5 * 60 * 1000, // 5 分钟后进行检查
                60 * 60 * 1000); // 每小时检查一次
    }

    private void startQuery(final int count) {
        if (mIsQuering) {
            return;
        }
        mIsQuering = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (count % 3 == 1 || count % 3 == 2) {
                    startQueryDB();
                    TrashCloudSharedPrefManager.setUpdateTimes();
                } else {
                    if (FeatureConfig.DEBUG_LOG) {
                        LogHelper.i(TrashPostContant.TAG, "执行云端路径更新=====");
                    }
                    TrashCloudSharedPrefManager.resetUpdateTimes();
                    addRequestData();
                    startQueryCloud();
                }
                mIsQuering = false;
            }
        }).start();
    }

    private void startQueryCloud() {
        String body = null;
        try {
            body = TrashPostBodyUtils.getPostBodyCloudPath();
            while (body != null) {
                if (TrashPostContant.OPEN) {
                    LogHelper.i(TrashPostContant.TAG, "=================================");
                    LogHelper.i(TrashPostContant.TAG, "云端路径请求：请求的json = " + body);
                }
                String lan = LanguageCompat.getLocaleString(CleanApplication.getInstance());
                String url = URLClOUD
                        + "?dulocal="
                        + lan
                        + "&lang=" + lan;

                //TODO 获取云配置
                Pair<Integer, String> resultPair = null;
                if (resultPair == null) {
                    return;
                }

                int codes = resultPair.first;
                String contentString = resultPair.second;

                if (TrashPostContant.OPEN) {
                    LogHelper.i(TrashPostContant.TAG, "云端路径请求： responseCode =  " + codes
                            + ",  contentString ="
                            + contentString);
                }

                if (codes == HttpURLConnection.HTTP_OK) {
                    List<PathUpdateInfo> datas = TrashPostBodyUtils
                            .handleTrashData(contentString, lan);
                    if (datas != null && datas.size() > 0) {
                        TrashDB.getInstance().updateDataHandler(null, datas, TrashDB.CLOUD_UPDATE);
                    }
                    body = TrashPostBodyUtils.getPostBodyCloudPath();
                } else {
                    body = null;
                    break;
                }
            }
        } catch (Exception e) {
            if (TrashPostContant.OPEN) {
                LogHelper.i(TrashPostContant.TAG, "云端路径请求：异常信息 " + e);
            }
        } finally {
            TrashCloudSharedPrefManager.setUpdateTime(System.currentTimeMillis());
        }
    }

    public interface QueryUnknowPathCallback {
        void onQueryStart();

        void onNetWorkError(int reponseCode);

        void onQueryComplete();

        void onQueryPartComplete(List<String> pathsList, List<PathUpdateInfo> infos);
    }

    private void startQueryDB() {
        TrashDB db = TrashDB.getInstance();
        String body = TrashPostBodyUtils.getPostBodyDB(String.valueOf(db.getDBVersion()),
                db.nativeUpdateMaxTime());
        try {
            if (TrashPostContant.OPEN) {
                LogHelper.i(TrashPostContant.TAG, "=================================");
                LogHelper.i(TrashPostContant.TAG, "本地数据库更新 ： 请求json = " + body);
            }
            String lan = LanguageCompat.getLocaleString(CleanApplication.getInstance());
            String url = URLDB
                    + "?dulocal="
                    + lan
                    + "&lang=" + lan;

            //TODO 获取云配置
            Pair<Integer, String> resultPair = null;
            if (resultPair == null) {
                return;
            }

            int responseCode = resultPair.first;
            if (TrashPostContant.OPEN) {
                LogHelper.i(TrashPostContant.TAG, "本地数据库更新：responseCode = " + responseCode + ", content = " + resultPair.second);
            }
            if (responseCode == HttpURLConnection.HTTP_OK) {
                String content = resultPair.second;
                if (content != null) {
                    List<PathUpdateInfo> infos = TrashPostBodyUtils.handleTrashData(content, lan);
                    db.updateDataHandler(null, infos, TrashDB.NATIVE_UPDATE);
                }
            }
        } catch (Exception e) {
            if (TrashPostContant.OPEN) {
                LogHelper.i(TrashPostContant.TAG, "本地数据库的更新，异常信息" + e);
            }
        }
        TrashCloudSharedPrefManager.setUpdateTime(System.currentTimeMillis());
    }

    public void startQueryUnknowPath(QueryUnknowPathCallback queryUnknowPathCallback) {
        long timeStart = System.currentTimeMillis();
        List<TrashUnknowPathData.NormalPath> normalList = TrashUnknowPathData.getInstance().getNomalPaths();
        List<TrashUnknowPathData.NormalPath> androidList = TrashUnknowPathData.getInstance().getSpecialPaths();

        List<String> unKownPaths = new ArrayList<String>();
        List<PathUpdateInfo> updateInfos = new ArrayList<PathUpdateInfo>();

        String body = null;
        try {
            body = TrashPostBodyUtils.getPostBodyUnKnowPath(normalList, androidList);
            if (TrashPostContant.OPEN) {
                LogHelper.i(TrashPostContant.TAG, "=================================");
                LogHelper.i(TrashPostContant.TAG, "未知路径请求 ：请求的 json =  " + body);
            }
            if (queryUnknowPathCallback != null && body != null) {
                queryUnknowPathCallback.onQueryStart();
            }
            String lan = LanguageCompat.getLocaleString(CleanApplication.getInstance());
            while (body != null) {
                String url = URLUNKNOW
                        + "?dulocal="
                        + lan
                        + "&lang=" + lan;


                //TODO 获取云配置
                Pair<Integer, String> resultPair = null;
                if (resultPair == null) {
                    return;
                }

                int code = resultPair.first;
                String contentSting = resultPair.second;
                if (TrashPostContant.OPEN) {
                    LogHelper.i(TrashPostContant.TAG,
                            "未知路径请求 ：responseCode = " + code + "contentString = " + contentSting);
                }
                //请求次数操作限制
                if (code == HttpURLConnection.HTTP_OK) {
                    List<String> normal = getPathList(androidList, normalList);
                    List<PathUpdateInfo> paths = TrashPostBodyUtils.handleTrashData(contentSting, lan);

                    if (normal != null) {
                        unKownPaths.addAll(normal);
                    }
                    if (paths != null) {
                        updateInfos.addAll(paths);
                    }

                    //回调callback,处理本次数据
                    if (queryUnknowPathCallback != null) {
                        queryUnknowPathCallback.onQueryPartComplete(normal, paths);
                    }
                    //生成下次请求的数据
                    normalList = TrashUnknowPathData.getInstance().getNomalPaths();
                    androidList = TrashUnknowPathData.getInstance().getSpecialPaths();
                    body = TrashPostBodyUtils.getPostBodyUnKnowPath(normalList, androidList);
                } else {
                    if (queryUnknowPathCallback != null) {
                        //更新数据到数据库之中
                        TrashDB.getInstance().updateDataHandler(unKownPaths, updateInfos, TrashDB.UNKNOWN_UPDATE);
                        queryUnknowPathCallback.onNetWorkError(code);
                    }
                    body = null;
                    break;
                }
            }
        } catch (Exception e) {
            if (TrashPostContant.OPEN) {
                LogHelper.i(TrashPostContant.TAG, "未知路径请求 ：异常信息" + e);
            }
        }
        if (queryUnknowPathCallback != null) {
            //更新数据到数据库之中
            TrashDB.getInstance().updateDataHandler(unKownPaths, updateInfos, TrashDB.UNKNOWN_UPDATE);
            queryUnknowPathCallback.onQueryComplete();

        }
        if (TrashPostContant.OPEN) {
            LogHelper.i(TrashPostContant.TAG, "未知路径请求 ：使用时间 = " + (System.currentTimeMillis() - timeStart));
        }
    }

    private List<String> getPathList(List<TrashUnknowPathData.NormalPath> androidList, List<TrashUnknowPathData.NormalPath> normal) {
        List<String> list = new ArrayList<String>();
        for (TrashUnknowPathData.NormalPath normalPath : normal) {
            StringBuffer buffer = new StringBuffer();
            if (normalPath.mLevelOne != null) {
                buffer.append(getPathPart(normalPath.mLevelOne));
            }
            if (normalPath.mLevelTwo != null) {
                buffer.append(getPathPart(normalPath.mLevelTwo));
            }
            if (normalPath.mLevelThree != null) {
                buffer.append(getPathPart(normalPath.mLevelThree));
            }
            buffer.append("/");
            list.add(buffer.toString());
        }
        for (TrashUnknowPathData.NormalPath normalPath : androidList) {
            StringBuffer buffer = new StringBuffer();
            buffer.append("/android/data");
            if (normalPath.mLevelOne != null) {
                buffer.append(getPathPart(normalPath.mLevelOne));
            }
            if (normalPath.mLevelTwo != null) {
                buffer.append(getPathPart(normalPath.mLevelTwo));
            }
            if (normalPath.mLevelThree != null) {
                buffer.append(getPathPart(normalPath.mLevelThree));
            }
            buffer.append("/");
            list.add(buffer.toString());
        }
        return list;
    }

    private String getPathPart(String part) {
        return "/" + part;
    }

    private void addRequestData() {
        List<FilePathBean> paths = TrashDB.getInstance().getCloudPath();
        if (paths == null || paths.isEmpty()) {
            if (FeatureConfig.DEBUG_LOG) {
                LogHelper.i(TrashPostContant.TAG, "数据库中未取到云端下发路径=====");
            }
            return;
        }
        if (FeatureConfig.DEBUG_LOG) {
            for (FilePathBean path : paths) {
                LogHelper.i(TrashPostContant.TAG, "数据库中取到云端下发路径=====" + path.toString());
            }
        }
        TrashCloudPathData instance = TrashCloudPathData.getInstance();
        for (FilePathBean filePathBean : paths) {
            instance.addTrashFromCloudItem(filePathBean.id,
                    filePathBean.updateTime);
        }
    }
}
